package br.com.wss.recursos;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class FindCursos {
	private String url;

	public FindCursos(String url) {
		this.url = url;
	}

	public Map<String, String> find() {
		Conexao conexao;
		ArrayList<String> list = new ArrayList<String>();
		InputStream in = null;
		try {
			conexao = new Conexao(url);
			in = conexao.getConecao();
			Document doc = null;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db;
			try {
				db = dbf.newDocumentBuilder();
				doc = db.parse(in);
			} catch (ParserConfigurationException e) {
				e.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();
			}

			doc.getDocumentElement().normalize();
			NodeList definitionElements = doc.getElementsByTagName("div");
			for (int i = 0; i < definitionElements.getLength(); i++) {
				Node itemNode = definitionElements.item(i);
				if (itemNode.getNodeType() == Node.ELEMENT_NODE) {
					Element definitionElement = (Element) itemNode;
					String atributo = definitionElement.getAttribute("id");

					if (atributo.equals("parent-fieldname-text")) {
						NodeList c = definitionElement
								.getElementsByTagName("p");
						for (int y = 1; y < c.getLength(); y++) {

							Element elementA = (Element) c.item(y);
							NodeList nodeListA = elementA
									.getElementsByTagName("a");
							for (int j = 0; j < nodeListA.getLength(); j++) {
								Element eleA = (Element) nodeListA.item(j);
								String l = eleA.getAttribute("href");
								String sub = l.substring(0, 1);
								if (!list.contains(l) && (!sub.equals("."))) {
									list.add(l);
								}
							}

						}

					}
				}
			}
			// }
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		MapWords words = new MapWords();
		HashMap<String, String> mapCursos = new HashMap<String, String>();
		for (String urlKey : list) {
			String[] vetor = urlKey.split("-");
			String nameCurso = "";
			for (int i = 0; i < vetor.length; i++) {
				String aux = words.find(vetor[i]);
				if (aux != null) {
					nameCurso = nameCurso.concat(aux).concat(" ");
				} else {
					nameCurso = nameCurso.concat(vetor[i]).concat(" ");
				}
			}
			mapCursos.put(nameCurso.trim(), urlKey);
		}

		return mapCursos;
	}

}
